package com.xauto.pioneer.appuser.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 所有适配器的抽象处理.
 * 
 * @author ShangGuan
 * @param <T>
 */
public abstract class AbsAdapter<T> extends BaseAdapter {

	private List<T> dataList = new ArrayList<T>();
	public LayoutInflater mInflater = null;
	public Activity context = null;
	private int layout = 0;
	
	/** 获取适配器数据源*/
	public List<T> getDataList() {
		return dataList;
	}

	/** 重置适配器*/
	public void release() {
		dataList.clear();
		dataList = null;
		context = null;
		mInflater = null;
	}

	/**
	 * 带参方法
	 * @param context
	 * @param layout
	 */
	public AbsAdapter(Activity context, int layout) {
		this.context = context;
		mInflater = LayoutInflater.from(context);
		this.layout = layout;
	}

	@Override
	public int getCount() {
		return dataList.size();
	}

	@Override
	public T getItem(int i) {
		if (getCount() <= 0 || i >= getCount())
			return null;
		return dataList.get(i);
	}

	@Override
	public long getItemId(int id) {
		return id;
	}

	@SuppressWarnings("unchecked")
	@Override
	public View getView(int position, View v, ViewGroup vg) {
		ViewHolder<T> vh = null;
		if (null == v) {
			v = mInflater.inflate(layout, null);
			vh = getHolder();
			vh.initViews(v, position);
			v.setTag(vh);
		} else {
			vh = (ViewHolder<T>) v.getTag();
		}

		if (getItem(position) != null) {
			vh.updateData(getItem(position), position);
			vh.doOthers(getItem(position), position);
		}
		return v;
	}

	public static interface ViewHolder<T> {
		public void initViews(View v, int position);

		public void updateData(T t, int position);

		public void doOthers(T t, int position);
	}
	public abstract ViewHolder<T> getHolder();

}
